package com.hanbang.chu_xing_gao_zhao.view_find_standard;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseDataActivity;
import com.hanbang.chu_xing_gao_zhao.entity.FindStandardData;
import com.hanbang.chu_xing_gao_zhao.myview.GridViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.cxgz_2.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 餐饮标准化—
 *
 * @author yang
 */
public class FindStandardClassifyActivity extends BaseDataActivity implements OnClickListener {
    /**
     * 请求参数
     */
    private RequestParams params;
    /**
     * 餐饮标准化列表
     */
    private PullToRefreshListView standardList;
    /**
     * 适配器
     */
    private ListViewAdapter adapter;
    /**
     * listView 头部
     */
    private View headerView;
    /**
     * 列表的数据
     */
    private ArrayList<FindStandardData> listData = new ArrayList<>();
    /**
     * 分类筛选
     */
    private LinearLayout classify;

    private int pageSize = 10;
    private int pageIndex = 1;
    private int category_id;
    private int sort_id = 0;
    private String title = "餐饮标准化";

    /**
     * 控制接口调用
     */
    int call = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_standard__classify_activity);
        initView();
        setOnClickListener();
    }


    /**
     * 初始化view
     * pageSize：分页大小，可为空
     * pageIndex：当前页码，为空默认1
     * category_id：类别，如果获取全部的话，为0
     * sort_id：排序方式，0综合 ，销量1,评价2，价格高3，价格低4，免费5
     */
    private void initView() {
        Intent intent = getIntent();
        category_id = intent.getIntExtra("category_id", 1);


        //标题设置
        setTitleMore(View.VISIBLE, View.VISIBLE, title, null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));
        //控件初始化
        standardList = (PullToRefreshListView) findViewById(R.id.lv_find_standard_activity_classify_list);
        ((FrameLayout) findViewById(R.id.fl_find_standard_activity_hint)).setVisibility(View.GONE);

        // 列表添加适配器
        adapter = new ListViewAdapter();
        headerView = getLayoutInflater().inflate(R.layout.item_find_standard_top_title_classify, standardList, false);
        classify = (LinearLayout) headerView.findViewById(R.id.ll_time_find_standard_top_title_classify);

        // 设置一个头布局
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                AbsListView.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(layoutParams);
//         把listView转换成正常的listView,时行添加头部
        ListView lv = standardList.getRefreshableView();
        lv.addHeaderView(headerView);


        standardList.setAdapter(adapter);


        //获取餐饮标准化的详情
        params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "password"));
        params.addBodyParameter("pageSize", pageSize + "");
        params.addBodyParameter("pageIndex", pageIndex + "");
        params.addBodyParameter("category_id", category_id + "");
        params.addBodyParameter("sort_id", sort_id + "");

        getHttpList(HttpInterfaces.GetGoodsList, params);

    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        classify.setOnClickListener(this);
        standardList.setMode(PullToRefreshBase.Mode.BOTH);

        //上下刷新
        standardList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                listData.clear();
                pageIndex = 1;
                params = new RequestParams();
                params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "password"));
                params.addBodyParameter("pageSize", pageSize + "");
                params.addBodyParameter("pageIndex", pageIndex + "");
                params.addBodyParameter("category_id", category_id + "");
                params.addBodyParameter("sort_id", sort_id + "");
                getHttpList(HttpInterfaces.GetGoodsList, params);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex++;
                params = new RequestParams();
                params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "password"));
                params.addBodyParameter("pageSize", pageSize + "");
                params.addBodyParameter("pageIndex", pageIndex + "");
                params.addBodyParameter("category_id", category_id + "");
                params.addBodyParameter("sort_id", sort_id + "");
                getHttpList(HttpInterfaces.GetGoodsList, params);

            }
        });

    }

    /**
     * 处理监听
     */


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_time_find_standard_top_title_classify:
                MorePopupWindowPublic popup = new MorePopupWindowPublic(FindStandardClassifyActivity.this, R.layout.item_popupwindow_public, sortId, 8);
                popup.showPopupWindow(classify, 2);
                popup.setOnClickCallback(new MorePopupWindowPublic.OnClickCallback() {
                    @Override
                    public void onClick(MorePopupWindowPublic morePopWindow, Object number, String content) {
                        sort_id = (int) number;
                        listData.clear();
                        adapter.notifyDataSetChanged();
                        RequestParams params = new RequestParams();
                        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                                FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                                FindStandardClassifyActivity.this, MySharedPreferences.USER_DATA, "password"));
                        params.addBodyParameter("pageSize", pageSize + "");
                        params.addBodyParameter("pageIndex", pageIndex + "");
                        params.addBodyParameter("category_id", category_id + "");
                        params.addBodyParameter("sort_id", sort_id + "");
                        getHttpList(HttpInterfaces.GetGoodsList, params);
                    }
                });
                break;
        }

    }

    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class ListViewAdapter extends BaseAdapter {


        public ListViewAdapter() {


        }

        @Override
        public int getCount() {

            return 1;
        }

        @Override
        public FindStandardData getItem(int position) {

            return listData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                convertView = getLayoutInflater().inflate(R.layout.item_find_standard_classify_gridview, null);
                ;
                viewHolder = new ViewHolder();

                // 子控件初始化

                viewHolder.gridView = (GridViewForScrollView) convertView.findViewById(R.id.item_find_standard_classify_gridview);


                convertView.setTag(viewHolder);// 把现有有item对象存起来
            } else {// 不是空复用
                viewHolder = (ViewHolder) convertView.getTag();

            }

            viewHolder.gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
            viewHolder.gridView.setAdapter(new GridViewAdapter());


            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            // 子控件主要是里面的数据

            private GridViewForScrollView gridView;

        }

    }


    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class GridViewAdapter extends BaseAdapter {


        public GridViewAdapter() {


        }

        @Override
        public int getCount() {


            return listData.size();
        }

        @Override
        public FindStandardData getItem(int position) {

            return listData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                convertView = getLayoutInflater().inflate(R.layout.item_find_standard_classify, null);
                UiUtils.applyFont(convertView);
                viewHolder = new ViewHolder();

                // 子控件初始化

                viewHolder.picture1 = (ImageView) convertView.findViewById(R.id.lv_item_find_standard_classify_picture1);
                viewHolder.name1 = (TextView) convertView.findViewById(R.id.tv_item_find_standard_classify_name1);
                viewHolder.price1 = (TextView) convertView.findViewById(R.id.tv_item_find_standard_classify_price1);
                viewHolder.bried1 = (TextView) convertView.findViewById(R.id.tv_item_find_standard_classify_brief);


                convertView.setTag(viewHolder);// 把现有有item对象存起来
            } else {// 不是空复用
                viewHolder = (ViewHolder) convertView.getTag();

            }

            final FindStandardData data = getItem(position);

            bitmapUtils.display(viewHolder.picture1, SystemTools.getHttpFileUrl(data.getImg_url()));
            bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_white);
            viewHolder.name1.setText(data.getTitle());

            viewHolder.price1.setText("¥" + String.valueOf(data.getPrice()));
            viewHolder.bried1.setText(data.getRemark());

            viewHolder.picture1.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(FindStandardClassifyActivity.this, FindStandardDetailsActivity.class);
                    intent.putExtra("id", data.getId());
                    intent.putExtra("title", data.getTitle());
                    startActivity(intent);
                }
            });


            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            // 子控件主要是里面的数据

            private ImageView picture1;
            private TextView name1;
            private TextView price1;
            private TextView bried1;

        }

    }


    /**
     * 获取课堂细节数据
     */
    private void getHttpList(String url, RequestParams params) {
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "加载中...") {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);

                    int result = json.getInt("Result");
                    if (result == 0) {
                        JSONArray jsonArray = json.getJSONArray("list");
                        //如果是空则停止接口的自动调用
                        if (jsonArray.length() == 0) {
                            call = -1;

                            MyToast.show(FindStandardClassifyActivity.this, "没有更多内容", 1);
                            standardList.onRefreshComplete();
                            return;
                        }
                        call = 0;
                        listData.addAll(JsonHelper.parseCollection(jsonArray, ArrayList.class, FindStandardData.class));
                        adapter.notifyDataSetChanged();
                        standardList.onRefreshComplete();
                    }

                } catch (Exception e) {
                    MyToast.show(FindStandardClassifyActivity.this, "网编异常请稍后再试", 1);
                    e.printStackTrace();
                }
            }
        });
    }


}


